﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using ApplicationLibrary;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.Preferences;
using ApplicationLibrary.SqlConnector;
using Plumber.Accounting.ModuleData;
using Plumber.Accounting.Preferences;
using Plumber.Masters.ModuleData;
using Plumber.Sales.ModuleData;

namespace Plumber.Accounting.Forms
{
    public partial class JournalEntries : ApplicationLibrary.DBManager.DocumentForm
    {
        private ComboBoxManager accountTypesFrom = null;
        private ComboBoxManager accountTypesTo = null;
        private bool bForcedCloseOpen = false;
        private Dictionary<string, Totals> DocumentList = null;
        private DRJournalEntryTotal dRJETotal = null;
        private DRJournalEntryTotalByType dRJETotals = null;
        private DRMasterType dRMasterType = null;
        private DRSalesInvoices dRSalesInvoices = null;
        private bool FromPrepareAuxData = false;
        private bool IsInLoad = false;
        private string oldText = string.Empty;
        private RRJournalEntryAfterMe rrJENotMe = null;
        private RUJournalEntryWithoutMe rUJENotMe = null;
        private AccountingPref AccountingPref = null;
        public BindableOject<bool> IsEditable = null;
        private BindableOject<int> taxRegister = null;
        private BindableOject<DateTime> DocumentDate = null;
        private BindableOject<string> DocumentNo = null;
        private BindableOject<string> Type = null;
        private BindableOject<string> Code = null;
        private BindableOject<int> invoiceType = null;

        public bool DontUpdateSale { set; private get; }
        public ExtendedDataGridView GetDataGrid { get { return dgwJournalEntries; } }
        public TextBox GetDescription { get { return txtDescription; } }
        public CalendarTextBox GetPostingDate { get { return ctbDate; } }
        public string JeNumber { get { return fncJournalNo.Text; } }

        public JournalEntries()
            : base(Properties.Resources.FN_JournalEntries)
        {
            InitializeComponent();
            AccountingPref = new PreferencesManager<AccountingPref>(this.Name, null).ReadPreference();
            keyControl = fncJournalNo;
        }

        #region Virtual Method

        protected override void FocusOnNew()
        {
        }

        protected override IRadarParameters GetKeyFromDocument()
        {
            return new RadarJournalEntryParam(fncJournalNo.Text);
        }

        protected override bool OnAfterAddNew()
        {
            IsEditable.Value = true;
            taxRegister.Value = TaxRegisterType.E_NORegister.Int();
            DocumentDate.Value = DocumentDate.Value.EmptyDate();
            DocumentNo.Value = "";
            Type.Value = "";
            Code.Value = "";
            invoiceType.Value = InvoiceType.E_NoInvoice.Int();
            return base.OnAfterAddNew();
        }

        protected override void OnAttachData()
        {
            dbManager = new dbmanagerJournalEntries("JournalEntriesForm", new RadarJournalEntry(false), this);
            dbManager.AddMaster(this, PL_JournalEntry.Name, true);
            dbManager.AddSlave(PL_JournalEntryDetail.Name, true);
            dbManager.AddRelation("JournalEntryDetail", PL_JournalEntry.JournalNo, PL_JournalEntryDetail.JournalNo, true);

            dRJETotal = new DRJournalEntryTotal();
            dRJETotals = new DRJournalEntryTotalByType();
            rUJENotMe = new RUJournalEntryWithoutMe();
            dRSalesInvoices = new DRSalesInvoices(true);
            dRMasterType = new DRMasterType(DRMasterType.Module.All);
            DocumentList = new Dictionary<string, Totals>();
            cbbTemplate.AttachDataReader<string>(new RRJETemplate(false), PL_JETemplate.Template, PL_JETemplate.Description, true);

            accountTypesFrom = new ComboBoxManager();
            accountTypesTo = new ComboBoxManager();
            IsEditable = new BindableOject<bool>();

            taxRegister = new BindableOject<int>();
            DocumentDate = new BindableOject<DateTime>();
            DocumentNo = new BindableOject<string>();
            Type = new BindableOject<string>();
            Code = new BindableOject<string>();
            invoiceType = new BindableOject<int>();

            RRMasterType rrMasterType = new RRMasterType();
            rrMasterType.Find();
            accountTypesFrom.AddValue<string>(null, "");
            accountTypesTo.AddValue<string>(null, "");

            for (int t = 0; t < rrMasterType.Count; t++)
            {
                if (rrMasterType.GetValue<MasterTypes>(PL_MasterType.MasterType, t) != MasterTypes.E_Administrator)
                {
                    accountTypesFrom.AddValue(rrMasterType.GetValue<string>(PL_MasterType.Code, t), rrMasterType.GetValue<string>(PL_MasterType.Description, t));
                    accountTypesTo.AddValue(rrMasterType.GetValue<string>(PL_MasterType.Code, t), rrMasterType.GetValue<string>(PL_MasterType.Description, t));
                }
            }
            accountTypesFrom.AttachTo(jec_Type);

            fncJournalNo.AttachCounterType(GlobalInfo.GetCounter(Properties.Resources.CN_JournalEntry), GlobalInfo.CurrentDate, dbManager.Transaction);

            ntbTo.Prefix = Properties.Resources.CurrencySimbol;
            ntbFrom.Prefix = Properties.Resources.CurrencySimbol;
        }

        protected override bool OnBeforeDelete()
        {
            if (!base.OnBeforeDelete())
                return false;

            if (AccountingPref.LockDocumentPayed && !CandDeleteRegistration())
            {
                MyMessageBox(Properties.Resources.Msg_JEAlredyPayed);
                return false;
            }

            return UpdateForSaveDelete(true);
        }

        protected override bool OnBeforeSave()
        {
            //dgwJournalEntries.Refresh();
            if (ntbFrom.Double != ntbTo.Double)
                if (MyMessageBox(Properties.Resources.Msg_JournalNotBalanced, Properties.Resources.Warning, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
                    return false;

            if (ctbDate.Today == ctbDate.EmptyDate)
            {
                MyMessageBox(Properties.Resources.Msg_MissingJournalDate, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }
            if (HasRowAtZero())
            {
                MyMessageBox(Properties.Resources.Msg_RowAtZero, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }

            if (HasEmptyRow())
            {
                MyMessageBox(Properties.Resources.Msg_MissingRows, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return false;
            }

            UpdateForSaveDelete(false);

            return base.OnBeforeSave();
        }

        protected override void OnBindData()
        {
            BindControl(fncJournalNo, PL_JournalEntry.JournalNo, NullValue.NotSet, Findable.YES);
            BindControl(ctbDate, PL_JournalEntry.PostingDate);
            BindControl(txtDescription, PL_JournalEntry.Description, Findable.YES);
            BindControl(ckbClose);

            BindObject(IsEditable, PL_JournalEntry.Editable);
            BindObject(taxRegister, PL_JournalEntry.TaxRegister);
            BindObject(DocumentDate, PL_JournalEntry.DocumentDate);
            BindObject(DocumentNo, PL_JournalEntry.DocumentNo);
            BindObject(Type, PL_JournalEntry.Type);
            BindObject(Code, PL_JournalEntry.Code);
            BindObject(invoiceType, PL_JournalEntry.InvoiceType);

            dgwJournalEntries.AutoGenerateColumns = false;
            dgwJournalEntries.DataSource = dbManager.SlaveBinding("JournalEntryDetail");

            BindColumn(jec_Line, PL_JournalEntryDetail.Line);
            BindColumn(jec_Type, PL_JournalEntryDetail.Type);
            BindColumn(jec_Code, PL_JournalEntryDetail.Code);
            BindColumn(jec_DocumentNo, PL_JournalEntryDetail.DocumentNo);
            BindColumn(jec_From, PL_JournalEntryDetail.From);
            BindColumn(jec_To, PL_JournalEntryDetail.To);
            BindColumn(jec_FromInvoice, PL_JournalEntryDetail.FromInvoice);
            BindColumn(jec_Closed, PL_JournalEntryDetail.Close);

            BindColumn(jec_Description, PL_JournalEntryDetail.Description);

            dgwJournalEntries.AddColumnChangeValue(PL_JournalEntryDetail.Type, new ExtendedDataGridView.DataGridViewValueChangeEventHandler(dgwJournalEntries_Type));
            dgwJournalEntries.AddColumnValidator(PL_JournalEntryDetail.Code, new ExtendedDataGridView.DataGridViewColumnValidatingEventHandler(dgwJournalEntries_Code));
            dgwJournalEntries.AddColumnChangeValue(PL_JournalEntryDetail.From, new ExtendedDataGridView.DataGridViewValueChangeEventHandler(dgwJournalEntries_FromAmountChange));
            dgwJournalEntries.AddColumnChangeValue(PL_JournalEntryDetail.To, new ExtendedDataGridView.DataGridViewValueChangeEventHandler(dgwJournalEntries_ToAmountChange));
            dgwJournalEntries.DataGridViewRowEnter += new DataGridViewCellEventHandler(dgwJournalEntries_DataGridViewRowEnter);
            dgwJournalEntries.DataGridViewRowRemoved += new DataGridViewRowsRemovedEventHandler(dgwJournalEntries_DataGridViewRowRemoved);
            dgwJournalEntries.DataGridViewRowAdded += new DataGridViewRowsAddedEventHandler(dgwJournalEntries_DataGridViewRowAdded);
            dgwJournalEntries.DataGridViewRowValidating += new DataGridViewCellCancelEventHandler(dgwJournalEntries_DataGridViewRowValidating);
            dgwJournalEntries.RowIndex = PL_JournalEntryDetail.Line;
            BindControl(dgwJournalEntries);

            BindControl(cbbTemplate);
            BindControl(btnLoad);
            BindControl(ntbFrom);
            BindControl(ntbTo);
            BindCounter(fncJournalNo);
        }

        protected override void OnDisableControlsForEdit()
        {
            cbbTemplate.Enabled = btnLoad.Enabled = false;
        }

        protected override void OnDisableControlsForNew()
        {
            ctbDate.Today = GlobalInfo.CurrentDate;
        }

        protected override void OnPrepareAuxData()
        {
            FromPrepareAuxData = true;
            ckbClose.Checked = GetRowClosed();
            FromPrepareAuxData = false;
            CalculateTotal();
        }

        private void CalculateTotal()
        {
            if (IsInLoad)
                return;

            ntbFrom.Double = 0;
            ntbTo.Double = 0;
            foreach (DataGridViewRow dr in dgwJournalEntries.Rows)
            {
                if (!dr.IsNewRow)
                {
                    ntbFrom.Double += DataGridViewRowValues.GetValue<double>(dr, PL_JournalEntryDetail.From);
                    ntbTo.Double += DataGridViewRowValues.GetValue<double>(dr, PL_JournalEntryDetail.To);
                }
            }
        }

        private bool CandDeleteRegistration()
        {
            bool payed = false;
            for (int t = 0; t < dbManager.GetDataTable(PL_JournalEntryDetail.Name).Rows.Count && !payed; t++)
            {
                string docNo = dbManager.GetColumn<string>(PL_JournalEntryDetail.DocumentNo, t);
                if (string.IsNullOrEmpty(docNo))
                    continue;

                string type = dbManager.GetColumn<string>(PL_JournalEntryDetail.Type, t);
                string code = dbManager.GetColumn<string>(PL_JournalEntryDetail.Code, t).ToString();

                string JEno = "", cod = "";
                double from, to;
                payed = SearchPayment(type, docNo, ref JEno, out from, out to, out cod);
            }
            return !payed;
        }

        private void dgwJournalEntries_DataGridViewRowAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            if (SilentMode || txtDescription.Text == string.Empty || IsInLoad)
                return;
            int nRow = e.RowIndex < e.RowCount
                            ? e.RowIndex
                            : e.RowIndex - 1;
            dgwJournalEntries.SetValue<string>(nRow, PL_JournalEntryDetail.Description, txtDescription.Text);
        }

        private void dgwJournalEntries_DataGridViewRowEnter(object sender, DataGridViewCellEventArgs e)
        {
            DoChangingRow(e);
            dgwJournalEntries[PL_JournalEntryDetail.Description].ReadOnly = string.IsNullOrEmpty(dgwJournalEntries.GetValue<string>(e.RowIndex, PL_JournalEntryDetail.Type));
        }

        private void dgwJournalEntries_DataGridViewRowRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            CalculateTotal();
        }

        private void dgwJournalEntries_DataGridViewRowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (DocumentMode == DBMode.Browse || IsInLoad)
                return;

            string typeCode = dgwJournalEntries.GetValue<string>(e.RowIndex, PL_JournalEntryDetail.Type);
            if (string.IsNullOrEmpty(typeCode))
                return;
            if (!dRMasterType.Find(typeCode))
                return;

            if (dRMasterType.GetValue<CodeMode>(PL_MasterType.CodeMode) == CodeMode.E_MustExists &&
                dgwJournalEntries.GetValue<string>(e.RowIndex, PL_JournalEntryDetail.Code) == string.Empty)
            {
                e.Cancel = true;
                string mess = string.Format(Properties.Resources.Msg_MissingCode, dRMasterType.GetValue<string>(PL_MasterType.Description, 0));
                MyMessageBox(this, mess,
                Properties.Resources.Error,
                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (dRMasterType.GetValue<bool>(PL_MasterType.DocNoRequired) &&
                dgwJournalEntries.GetValue<string>(e.RowIndex, PL_JournalEntryDetail.DocumentNo) == string.Empty)
            {
                e.Cancel = true;
                MyMessageBox(this, Properties.Resources.Msg_MissingDocNo,
                Properties.Resources.Error,
                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (DocumentMode == DBMode.Browse)
                return;
        }

        private bool HasRowAtZero()
        {
            foreach (DataGridViewRow dr in dgwJournalEntries.Rows)
            {
                if (dr.IsNewRow)
                    continue;
                if (DataGridViewRowValues.GetValue<double>(dr, PL_JournalEntryDetail.From) == 0 &&
                    DataGridViewRowValues.GetValue<double>(dr, PL_JournalEntryDetail.To) == 0)
                    return true;
            }

            return false;
        }

        private bool HasEmptyRow()
        {
            int rowFound = 0;
            foreach (DataGridViewRow dr in dgwJournalEntries.Rows)
            {
                if (dr.IsNewRow)
                    continue;
                if (string.IsNullOrEmpty(DataGridViewRowValues.GetValue<string>(dr, PL_JournalEntryDetail.Type)))
                    continue;
                if (DataGridViewRowValues.GetValue<double>(dr, PL_JournalEntryDetail.From) == 0 &&
                    DataGridViewRowValues.GetValue<double>(dr, PL_JournalEntryDetail.To) == 0)
                    continue;
                rowFound++;
            }

            return rowFound == 0;
        }

        private bool SearchPayment(string type, string docNo, ref string JENo, out double from, out double to, out string code)
        {
            from = to = 0;
            code = string.Empty;

            if (rrJENotMe == null)
                rrJENotMe = new RRJournalEntryAfterMe();

            if (rrJENotMe.Find(type, docNo, fncJournalNo.Text))
            {
                for (int t = 0; t < rrJENotMe.Count; t++)
                {
                    if (rrJENotMe.GetValue<double>(PL_JournalEntryDetail.To, t) != 0)
                    {
                        to += rrJENotMe.GetValue<double>(PL_JournalEntryDetail.To, t);
                    }
                    if (rrJENotMe.GetValue<double>(PL_JournalEntryDetail.From, t) != 0)
                    {
                        JENo = rrJENotMe.GetValue<string>(PL_JournalEntryDetail.JournalNo, t);
                        code = rrJENotMe.GetValue<string>(PL_JournalEntryDetail.Code, t);
                        from += rrJENotMe.GetValue<double>(PL_JournalEntryDetail.From, t);
                    }
                }
            }

            return from != 0 && to != 0;
        }

        private void UpdateAllJEntry(string docNo, string type, string code, string journalNo, double totalFrom, double totalTo)
        {
            bool closed = totalFrom == totalTo;
            if (rUJENotMe.Find(docNo, type, code, journalNo))
            {
                for (int t = 0; t < rUJENotMe.Count; t++)
                    rUJENotMe.SetValue<bool>(PL_JournalEntryDetail.Close, t, closed);
            }
            rUJENotMe.Update();

            // TODO AGGIORARE NOTA DI CREDITO
            // Aggiorno la fattura
            if (dRSalesInvoices.Find(global::InvoiceType.E_InvoiceEm, docNo) &&
                dRSalesInvoices.GetValue<string>(PL_SalesInvoices.Type) == type &&
                dRSalesInvoices.GetValue<string>(PL_SalesInvoices.Master) == code)
            {
                dRSalesInvoices.SetValue<double>(PL_SalesInvoices.AmountPayed, totalFrom);
                dRSalesInvoices.SetValue<bool>(PL_SalesInvoices.SalePayed, closed);
                dRSalesInvoices.SetValue<DateTime>(PL_SalesInvoices.PaymentDate, closed
                                                        ? ctbDate.Today
                                                        : PL_SalesInvoices.EmptyDate);

                dRSalesInvoices.Update();
            }

            // Mi cerco nel documento corrente e mi aggiorno
            for (int t = 0; t < dbManager.GetDataTable(PL_JournalEntryDetail.Name).Rows.Count && !bForcedCloseOpen; t++)
            {
                if (dbManager.GetColumn<string>(PL_JournalEntryDetail.DocumentNo, t) == docNo)
                    dbManager.SetColumn<bool>(PL_JournalEntryDetail.Close, t, closed);
            }
        }

        private bool UpdateForSaveDelete(bool isDelete)
        {
            txtDescription.Focus();
            dgwJournalEntries.EndEdit();
            if (dgwJournalEntries.CurrentCell.RowIndex != 0)
                dgwJournalEntries.CurrentCell = dgwJournalEntries[PL_JETemplateDetail.From, 0];

            DocumentList.Clear();

            for (int t = 0; t < dbManager.GetDataTable(PL_JournalEntryDetail.Name).Rows.Count; t++)
            {
                DataRowState drState = dbManager.GetDataRow(PL_JournalEntryDetail.Name, t).RowState;
                if ((drState == DataRowState.Unchanged && !isDelete) ||
                    string.IsNullOrEmpty(dbManager.GetColumn<string>(PL_JournalEntryDetail.DocumentNo, t)))
                    continue;

                //if (drState == DataRowState.Modified &&
                //        dbManager.GetColumn<double>(PL_JournalEntryDetail.From, t, DataRowVersion.Original) ==  dbManager.GetColumn<double>(PL_JournalEntryDetail.From, t) &&
                //        dbManager.GetColumn<double>(PL_JournalEntryDetail.To, t, DataRowVersion.Original) ==  dbManager.GetColumn<double>(PL_JournalEntryDetail.To, t))
                //    continue;

                string docNo = dbManager.GetColumn<string>(PL_JournalEntryDetail.DocumentNo, t);
                string type = dbManager.GetColumn<string>(PL_JournalEntryDetail.Type, t);
                string code = dbManager.GetColumn<string>(PL_JournalEntryDetail.Code, t).ToString();

                string key = string.Concat(docNo, " ", type, " ", code);

                if (!DocumentList.ContainsKey(key))
                    DocumentList.Add(key, new Totals(docNo, type, code, 0, 0));

                double totFrom = 0, totTo = 0;
                switch (drState)
                {
                    case DataRowState.Added:
                        if (isDelete)
                        {
                            totFrom -= dbManager.GetColumn<double>(PL_JournalEntryDetail.From, t);
                            totTo -= dbManager.GetColumn<double>(PL_JournalEntryDetail.To, t);
                        }
                        else
                        {
                            totFrom += dbManager.GetColumn<double>(PL_JournalEntryDetail.From, t);
                            totTo += dbManager.GetColumn<double>(PL_JournalEntryDetail.To, t);
                        }
                        break;

                    case DataRowState.Modified:
                        if (isDelete)
                        {
                            totFrom -= dbManager.GetColumn<double>(PL_JournalEntryDetail.From, t);
                            totTo -= dbManager.GetColumn<double>(PL_JournalEntryDetail.To, t);
                        }
                        else
                        {
                            totFrom -= dbManager.GetColumn<double>(PL_JournalEntryDetail.From, t, DataRowVersion.Original);
                            totTo -= dbManager.GetColumn<double>(PL_JournalEntryDetail.To, t, DataRowVersion.Original);
                            totFrom += dbManager.GetColumn<double>(PL_JournalEntryDetail.From, t);
                            totTo += dbManager.GetColumn<double>(PL_JournalEntryDetail.To, t);
                        }
                        break;

                    case DataRowState.Unchanged:
                        if (isDelete)
                            totFrom -= dbManager.GetColumn<double>(PL_JournalEntryDetail.From, t, DataRowVersion.Original);
                        totTo -= dbManager.GetColumn<double>(PL_JournalEntryDetail.To, t, DataRowVersion.Original);
                        break;

                    case DataRowState.Deleted:
                        totFrom -= dbManager.GetColumn<double>(PL_JournalEntryDetail.From, t, DataRowVersion.Original);
                        totTo -= dbManager.GetColumn<double>(PL_JournalEntryDetail.To, t, DataRowVersion.Original);
                        break;
                }

                DocumentList[key].totFrom += totFrom;
                DocumentList[key].totTo += totTo;
            }

            if (DocumentList.Count > 0)
                UpdateJournalEntries();

            return true;
        }

        private void UpdateJournalEntries()
        {
            foreach (KeyValuePair<string, Totals> item in DocumentList)
                if (item.Value.totFrom != 0 || item.Value.totTo != 0)
                {
                    // Mi faccio restituire il totale senza questa registrazione
                    dRJETotals.Find(item.Value.DocNo, item.Value.Type, item.Value.Code);
                    double totalFrom = dRJETotals.GetValue<double>(PL_JournalEntryDetail.From) + item.Value.totFrom;
                    double totalTo = dRJETotals.GetValue<double>(PL_JournalEntryDetail.To) + item.Value.totTo;

                    UpdateAllJEntry(item.Value.DocNo, item.Value.Type, item.Value.Code, fncJournalNo.Text, totalFrom, totalTo);
                }
        }

        #endregion

        public int AddNewRow(string masterType, string docNo, string code, double from, double to, string desc, bool fromInvoie, bool closed)
        {
            DataRowView drw = dgwJournalEntries.AddNewRow(PL_JournalEntryDetail.Line);

            DataRowViewValues.SetValue<string>(drw, PL_JournalEntryDetail.Type, masterType);
            DataRowViewValues.SetValue<string>(drw, PL_JournalEntryDetail.DocumentNo, docNo);
            DataRowViewValues.SetValue<string>(drw, PL_JournalEntryDetail.Code, code);
            DataRowViewValues.SetValue<double>(drw, PL_JournalEntryDetail.From, from);
            DataRowViewValues.SetValue<double>(drw, PL_JournalEntryDetail.To, to);
            DataRowViewValues.SetValue<string>(drw, PL_JournalEntryDetail.Description, desc);
            DataRowViewValues.SetValue<bool>(drw, PL_JournalEntryDetail.FromInvoice, fromInvoie);
            DataRowViewValues.SetValue<bool>(drw, PL_JournalEntryDetail.Close, closed);
            return DataRowViewValues.GetValue<int>(drw, PL_JournalEntryDetail.Line);
        }

        protected override void OnCustomButtonClick(ToolStripButton button)
        {
            if (button.Name == "Receipt")
            {
                EmittedDocJournalEntries je = new EmittedDocJournalEntries();
                AddListDocNo(je.ListDocumentNo);
                OpenNewForm(je, true);
                if (je.DialogResult == System.Windows.Forms.DialogResult.OK)
                    LoadEmittedDoc(je.List, je.MasterType, je.FromType, je.FromCode, je.Total, InvoiceType.E_InvoiceEm);
            }

            if (button.Name == "CreditNoteEm")
            {
                CreditNoteEmittedDocJournalEntries je = new CreditNoteEmittedDocJournalEntries();
                AddListDocNo(je.ListDocumentNo);
                OpenNewForm(je, true);
                if (je.DialogResult == System.Windows.Forms.DialogResult.OK)
                    LoadReceivedDoc(je.List, je.MasterType, je.FromType, je.FromCode, je.Total, InvoiceType.E_CreditNoteEm);
            }

            if (button.Name == "Payment")
            {
                ReceivedDocJournalEntries je = new ReceivedDocJournalEntries();
                AddListDocNo(je.ListDocumentNo);
                OpenNewForm(je, true);
                if (je.DialogResult == System.Windows.Forms.DialogResult.OK)
                    LoadReceivedDoc(je.List, je.MasterType, je.FromType, je.FromCode, je.Total, InvoiceType.E_InvoiceRc);
            }

            if (button.Name == "CreditNoteRc")
            {
                CreditNoteReceivedDocJournalEntries je = new CreditNoteReceivedDocJournalEntries();
                AddListDocNo(je.ListDocumentNo);
                OpenNewForm(je, true);
                if (je.DialogResult == System.Windows.Forms.DialogResult.OK)
                    LoadEmittedDoc(je.List, je.MasterType, je.FromType, je.FromCode, je.Total, InvoiceType.E_CreditNoteRc);
            }
        }

        protected override void OnCustomizeToolbar(ToolStrip toolstrip)
        {
            AddCustomButton("Receipt", Properties.Resources.T_Receipt, Properties.Resources.B_Receipt, true);
            AddCustomButton("Payment", Properties.Resources.T_Payment, Properties.Resources.B_Payment, true);
            AddCustomButton("CreditNoteEm", Properties.Resources.T_CreditNoteEm, Properties.Resources.B_Payment, true);
            AddCustomButton("CreditNoteRc", Properties.Resources.T_CreditNoteRc, Properties.Resources.B_Receipt , true);
        }

        protected override bool OnEnableToolbarButtons(ToolStripButton button)
        {
            if (button.Name == "Receipt")
                return dbManager.Status == DBMode.Edit;

            if (button.Name == "Payment")
                return dbManager.Status == DBMode.Edit;

            if (button.Name == "CreditNoteEm")
                return dbManager.Status == DBMode.Edit;

            if (button.Name == "CreditNoteRc")
                return dbManager.Status == DBMode.Edit;

            if (button.Name == "tbnEdit")
                return dbManager.GetColumn<bool>(PL_JournalEntry.Editable, 0) || !AccountingPref.LockDocumentFromSale;

            return base.OnEnableToolbarButtons(button);
        }

        private void AddListDocNo(List<string> listDocNo)
        {
            foreach (DataGridViewRow dr in dgwJournalEntries.Rows)
            {
                string docNo;
                if (!dr.IsNewRow)
                {
                    docNo = DataGridViewRowValues.GetValue<string>(dr, PL_JournalEntryDetail.DocumentNo);
                    if (docNo != "")
                        listDocNo.Add(docNo);
                }
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DRJETemplate drJETemplate = new DRJETemplate();
            RRJETemplateDetail rrJEDetail = new RRJETemplateDetail();

            IsInLoad = true;

            if (drJETemplate.Find(cbbTemplate.GetValue<string>()))
            {
                txtDescription.Text = drJETemplate.GetValue<string>(PL_JETemplate.Description);
                if (rrJEDetail.Find(cbbTemplate.GetValue<string>()))
                    for (int t = 0; t < rrJEDetail.Count; t++)
                    {
                        AddNewRow(rrJEDetail.GetValue<string>(PL_JETemplateDetail.Type, t),
                                    rrJEDetail.GetValue<string>(PL_JETemplateDetail.DocumentNo, t),
                                    rrJEDetail.GetValue<string>(PL_JETemplateDetail.Code, t),
                                    rrJEDetail.GetValue<double>(PL_JETemplateDetail.From, t),
                                    rrJEDetail.GetValue<double>(PL_JETemplateDetail.To, t),
                                    rrJEDetail.GetValue<string>(PL_JETemplateDetail.Description, t),
                                    false, false);
                    }
            }
            IsInLoad = false;
            if (dgwJournalEntries.RowCount > 1)
            {
                dgwJournalEntries.DataGridViewRowValidating -= new DataGridViewCellCancelEventHandler(dgwJournalEntries_DataGridViewRowValidating);
                dgwJournalEntries.CurrentCell = dgwJournalEntries[PL_JETemplateDetail.From, 0];
                dgwJournalEntries.DataGridViewRowValidating += new DataGridViewCellCancelEventHandler(dgwJournalEntries_DataGridViewRowValidating);
            }
        }

        private void ChangeCloseStatusRow(bool status)
        {
            bForcedCloseOpen = true;
            foreach (DataGridViewRow dr in dgwJournalEntries.Rows)
                if (!dr.IsNewRow)
                    DataGridViewRowValues.SetValue<bool>(dr, PL_JournalEntryDetail.Close, status);
        }

        private void ckbClose_CheckedChanged(object sender, EventArgs e)
        {
        }

        private void ckbClose_CheckStateChanged(object sender, EventArgs e)
        {
            if (DocumentMode == DBMode.Browse || IsNew || FromPrepareAuxData)
                return;

            if (MyMessageBox(
                    ckbClose.Checked
                        ? Properties.Resources.Msg_CloseJE
                        : Properties.Resources.Msg_OpenJE,
                     Properties.Resources.Warning, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.Yes)
                ChangeCloseStatusRow(ckbClose.Checked);
            else
                ckbClose.Checked = !ckbClose.Checked;
        }

        private string CreateListDocNo(ListView.ListViewItemCollection list)
        {
            string docs = string.Empty;
            foreach (ListViewItem lvi in list)
                if (lvi.Checked)
                    docs += lvi.SubItems[PL_JournalEntryDetail.DocumentNo.Name].Text.Replace(" ", string.Empty) + " ";
            return docs;
        }

        private void CreateTaxRow(object sender, EventArgs e)
        {
            dgwJournalEntries.CommitEdit(DataGridViewDataErrorContexts.Commit);
            double colFrom = DataGridViewRowValues.GetValue<double>(dgwJournalEntries.CurrentRow, PL_JournalEntryDetail.From);
            double colTo = DataGridViewRowValues.GetValue<double>(dgwJournalEntries.CurrentRow, PL_JournalEntryDetail.To);

            if (colTo > 0)
            {
                AddNewRow(AccountingPref.SaleTax, "", "", 10, 20, "desc", false, false);
            }
            else
            {
            }
        }

        private void dgwJournalEntries_DataGridViewDoubleClickCell(object sender, DataGridViewDoubleClickArgs e)
        {
            if (e.ColumnName == PL_JournalEntryDetail.Code.Name)
            {
                string typeCode = dgwJournalEntries.GetValue<string>(e.Row, PL_JournalEntryDetail.Type);
                if (dRMasterType.Find(typeCode))
                {
                    if (dRMasterType.GetValue<bool>(PL_MasterType.IsAccountingType))
                    {
                        Plumber.Accounting.Forms.AccountingMasters frm = (Plumber.Accounting.Forms.AccountingMasters)GlobalInfo.OpenForm("Plumber.Plumber.Accounting.Forms.AccountingMasters", false);
                        string type = dgwJournalEntries.GetValue<string>(e.Row, PL_Masters.Type);
                        frm.FindRecord(new RadarMasterParam(type, e.CellValue));
                    }
                    else
                    {
                        Plumber.Masters.Forms.Masters frm = (Plumber.Masters.Forms.Masters)GlobalInfo.OpenForm("Plumber.Plumber.Masters.Forms.Masters", false);
                        string type = dgwJournalEntries.GetValue<string>(e.Row, PL_Masters.Type);
                        frm.FindRecord(new RadarMasterParam(type, e.CellValue));
                    }
                }
            }
        }

        public string dgwJournalEntries_Code(object sender, DataGridViewCellValidatingEventArgs e)
        {
            string value;
            IRadarParameters iParam = jec_Code.RadarForm.GetRadarParameters(e.FormattedValue.ToString());
            e.Cancel = !jec_Code.RadarForm.ValidateValue(iParam, out value);
            return value;
        }

        private void dgwJournalEntries_FromAmountChange(object sender, DataGridViewCellEventArgs e)
        {
            if (dgwJournalEntries.RowCount == 3 && !IsInLoad)
            {
                int rowToChange = e.RowIndex == 1 ? 0 : 1;
                double valFrom = dgwJournalEntries.GetValue<double>(e.RowIndex, PL_JETemplateDetail.From);
                double valTo = dgwJournalEntries.GetValue<double>(rowToChange, PL_JETemplateDetail.To);
                if (valFrom != valTo)
                    dgwJournalEntries.SetValue<double>(rowToChange, PL_JETemplateDetail.To, valFrom);
            }
            CalculateTotal();
        }

        private void dgwJournalEntries_ToAmountChange(object sender, DataGridViewCellEventArgs e)
        {
            if (dgwJournalEntries.RowCount == 3 && !IsInLoad)
            {
                int rowToChange = e.RowIndex == 1 ? 0 : 1;
                double valTo = dgwJournalEntries.GetValue<double>(e.RowIndex, PL_JETemplateDetail.To);
                double valFrom = dgwJournalEntries.GetValue<double>(rowToChange, PL_JETemplateDetail.From);
                if (valFrom != valTo)
                    dgwJournalEntries.SetValue<double>(rowToChange, PL_JETemplateDetail.From, valTo);
            }
            CalculateTotal();
        }

        private void dgwJournalEntries_Type(object sender, DataGridViewCellEventArgs e)
        {
            DoChangingRow(e);

            if (dgwJournalEntries[PL_JournalEntryDetail.DocumentNo].ReadOnly)
                dgwJournalEntries.SetValue<string>(e.RowIndex, PL_JournalEntryDetail.DocumentNo, "");
            if (dgwJournalEntries[PL_JournalEntryDetail.Description].ReadOnly)
                dgwJournalEntries.SetValue<string>(e.RowIndex, PL_JournalEntryDetail.Description, "");
        }

        private void DoChangingRow(DataGridViewCellEventArgs e)
        {
            string typeCode = dgwJournalEntries.GetValue<string>(e.RowIndex, PL_JournalEntryDetail.Type);
            dgwJournalEntries[PL_JournalEntryDetail.Code].ReadOnly = string.IsNullOrEmpty(typeCode);
            dgwJournalEntries[PL_JournalEntryDetail.From].ReadOnly = string.IsNullOrEmpty(typeCode);
            dgwJournalEntries[PL_JournalEntryDetail.To].ReadOnly = string.IsNullOrEmpty(typeCode);

            if (string.IsNullOrEmpty(typeCode))
                return;

            RadarMasterForm.Module module = RadarMasterForm.Module.All;
            if (dRMasterType.Find(typeCode))
            {
                module = dRMasterType.GetValue<bool>(PL_MasterType.IsAccountingType)
                            ? RadarMasterForm.Module.Accounting
                            : RadarMasterForm.Module.Master;
            }
            jec_Code.AttachCodeType(typeCode);
            jec_Code.MustExistData = true;

            if (jec_Code.RadarForm != null)
            {
                jec_Code.RadarForm.FilterType = typeCode;
                ((RadarMasterForm)jec_Code.RadarForm).ModuleType = module;
            }
            else
                jec_Code.RadarForm = new RadarMasterForm(typeCode, module);

            if (dRMasterType.Find(typeCode))
                dgwJournalEntries[PL_JournalEntryDetail.Code].ReadOnly = dRMasterType.GetValue<CodeMode>(PL_MasterType.CodeMode) == CodeMode.E_IsEmpty;
            else
                dgwJournalEntries[PL_JournalEntryDetail.Code].ReadOnly = false;

            if (dgwJournalEntries[PL_JournalEntryDetail.Code].ReadOnly)
                dgwJournalEntries.SetValue<string>(e.RowIndex, PL_JournalEntryDetail.Code, "");

            dgwJournalEntries[PL_JournalEntryDetail.Description].ReadOnly = string.IsNullOrEmpty(dgwJournalEntries.GetValue<string>(e.RowIndex, PL_JournalEntryDetail.Type));
            dgwJournalEntries[PL_JournalEntryDetail.DocumentNo].ReadOnly = dRMasterType.GetValue<bool>(PL_MasterType.CanReceiveInvoice);
        }

        private DataGridViewRow FindPrimaryRow(string fromType, string fromCode)
        {
            foreach (DataGridViewRow dr in dgwJournalEntries.Rows)
            {
                if (!dr.IsNewRow)
                {
                    int bCode = string.Compare(DataGridViewRowValues.GetValue<string>(dr, PL_JournalEntryDetail.Code), fromCode, StringComparison.Ordinal);
                    if (DataGridViewRowValues.GetValue<string>(dr, PL_JournalEntryDetail.Type) == fromType &&
                        DataGridViewRowValues.GetValue<string>(dr, PL_JournalEntryDetail.Code) == fromCode)
                        return dr;
                }
            }
            return null;
        }

        private bool GetRowClosed()
        {
            bool isClose = true;
            bool atLeastOne = false;

            foreach (DataGridViewRow dr in dgwJournalEntries.Rows)
                if (!dr.IsNewRow && DataGridViewRowValues.GetValue<string>(dr, PL_JournalEntryDetail.Code) != "")
                {
                    isClose &= DataGridViewRowValues.GetValue<bool>(dr, PL_JournalEntryDetail.Close);
                    atLeastOne = true;
                }
            return isClose && atLeastOne;
        }

        private void LoadEmittedDoc(ListView.ListViewItemCollection list, string masterType, string fromType, string fromCode, double total, InvoiceType invType)
        {
            IsInLoad = true;
            string desc = string.Empty;
            DataGridViewRow dvrPrimary = FindPrimaryRow(fromType, fromCode);
            DataGridViewRow dvrBankRes = null;
            if (list.Count > 0)
            {
                ListViewItemPayment lvi = GetFirstChecked(list) as ListViewItemPayment;
                desc = string.Format(GetStringFormat(lvi.SubItems[PL_JournalEntry.InvoiceType.Name].Text, true), CreateListDocNo(list), "");

                if (desc.Length > PL_JournalEntry.Description.Len)
                    desc = desc.Substring(0, PL_JournalEntry.Description.Len);

                if (dvrPrimary == null)
                {
                    AddNewRow(fromType, "", fromCode, 0, total, desc, false, false);
                    dvrPrimary = FindPrimaryRow(fromType, fromCode);
                }
                else
                {
                    total += DataGridViewRowValues.GetValue<double>(dvrPrimary, PL_JournalEntryDetail.To);
                    DataGridViewRowValues.SetValue<double>(dvrPrimary, PL_JournalEntryDetail.To, total);
                }

                ntbTo.Double = total;
                txtDescription.Text = desc;
            }
            double bankRest = 0;
            foreach (ListViewItemPayment lvi in list)
            {
                if (lvi.Checked)
                {
                    desc = string.Format(GetStringFormat(lvi.SubItems[PL_JournalEntry.InvoiceType.Name].Text, false), lvi.SubItems[PL_JournalEntryDetail.DocumentNo.Name].Text, lvi.SubItems[PL_JournalEntry.PostingDate.Name].Text);
                    AddNewRow(masterType, lvi.SubItems[PL_JournalEntryDetail.DocumentNo.Name].Text, lvi.SubItems[PL_JournalEntryDetail.Code.Name].Text, lvi.Total - lvi.Partial, 0, desc, false, false);

                    if (lvi.HasBankRestraint)
                    {
                        bankRest = Math.Round((lvi.Total - lvi.Partial) / 1.22 * 0.08, 2);
                        total = total - bankRest;
                        DataGridViewRowValues.SetValue<double>(dvrPrimary, PL_JournalEntryDetail.To, total);
                        dvrBankRes = FindPrimaryRow(AccountingPref.BankRestraint, AccountingPref.BankRestraintCode);
                        if (dvrBankRes == null)
                        {
                            AddNewRow(AccountingPref.BankRestraint, "", AccountingPref.BankRestraintCode, 0, bankRest, "Ritenuta 8%", false, false);
                            dvrBankRes = FindPrimaryRow(AccountingPref.BankRestraint, AccountingPref.BankRestraintCode);
                        }
                    }
                    else bankRest = 0;
                    
                    ntbFrom.Double += lvi.Total - lvi.Partial;
                }
            }

            IsInLoad = false;
        }

        private void LoadReceivedDoc(ListView.ListViewItemCollection list, string masterType, string fromType, string fromCode, double total, InvoiceType invType)
        {
            IsInLoad = true;
            string desc = string.Empty;
            if (list.Count > 0)
            {
                desc = string.Format(GetStringFormat(GetFirstChecked(list).SubItems[PL_JournalEntry.InvoiceType.Name].Text, true), CreateListDocNo(list), "");
                if (desc.Length > PL_JournalEntry.Description.Len)
                    desc = desc.Substring(0, PL_JournalEntry.Description.Len);
                DataGridViewRow dvr = FindPrimaryRow(fromType, fromCode);
                if (dvr == null)
                    AddNewRow(fromType, "", fromCode, total, 0, desc, false, false);
                else
                {
                    total += DataGridViewRowValues.GetValue<double>(dvr, PL_JournalEntryDetail.From);
                    DataGridViewRowValues.SetValue<double>(dvr, PL_JournalEntryDetail.From, total);
                }

                ntbFrom.Double = total;
                txtDescription.Text = desc;
            }
            foreach (ListViewItem lvi in list)
            {
                if (lvi.Checked)
                {
                    desc = string.Format(GetStringFormat(lvi.SubItems[PL_JournalEntry.InvoiceType.Name].Text, false), lvi.SubItems[PL_JournalEntryDetail.DocumentNo.Name].Text, lvi.SubItems[PL_JournalEntry.PostingDate.Name].Text);
                    Double To = Double.Parse(lvi.SubItems["Partial"].Tag.ToString());
                    AddNewRow(masterType, lvi.SubItems[PL_JournalEntryDetail.DocumentNo.Name].Text, lvi.SubItems[PL_JournalEntryDetail.Code.Name].Text, 0, To, desc, false, false);
                    ntbTo.Double += To;
                }
            }
            CalculateTotal();
            IsInLoad = false;
        }

        private string GetStringFormat(string sText, bool header)
        {
            if (sText == InvoiceType.E_InvoiceEm.GetFormatValue())
                return header
                        ? Properties.Resources.Msg_CollectInvoices
                        : Properties.Resources.Msg_CollectInvoice;
            else if (sText == InvoiceType.E_InvoiceRc.GetFormatValue())
                return header
                        ? Properties.Resources.Msg_PayedInvoices
                        : Properties.Resources.Msg_PayedInvoice;
            else if (sText == InvoiceType.E_CreditNoteRc.GetFormatValue())
                return header
                        ? Properties.Resources.Msg_CollectCreditNotes
                        : Properties.Resources.Msg_CollectCreditNote;
            else if (sText == InvoiceType.E_CreditNoteEm.GetFormatValue())
                return header
                        ? Properties.Resources.Msg_PayedCreditNotes
                        : Properties.Resources.Msg_PayedCreditNote;
            else if (sText == InvoiceType.E_DebitNoteEm.GetFormatValue())
                return header
                        ? Properties.Resources.Msg_CollectDebitNotes
                        : Properties.Resources.Msg_CollectDebitNote;
            else if (sText == InvoiceType.E_DebitNoteRc.GetFormatValue())
                return header
                        ? Properties.Resources.Msg_PayedDebitNotes
                        : Properties.Resources.Msg_PayedDebitNote;
            return header
                    ? "{0}"
                    : "{0} {1}";
        }

        private ListViewItem GetFirstChecked(ListView.ListViewItemCollection list)
        {
            foreach (ListViewItem lvi in list)
                if (lvi.Checked)
                    return lvi;

            return list[0];
        }

        private void txtDescription_Enter(object sender, EventArgs e)
        {
            oldText = txtDescription.Text;
        }

        private void txtDescription_Validating(object sender, CancelEventArgs e)
        {
            foreach (DataGridViewRow dr in dgwJournalEntries.Rows)
            {
                if (!dr.IsNewRow)
                {
                    if (DataGridViewRowValues.GetValue<string>(dr, PL_JournalEntryDetail.Description) == null)
                        DataGridViewRowValues.SetValue<string>(dr, PL_JournalEntryDetail.Description, txtDescription.Text);
                    else
                    {
                        string desc = DataGridViewRowValues.GetValue<string>(dr, PL_JournalEntryDetail.Description);
                        if (desc.Contains(oldText) && desc != string.Empty && oldText != string.Empty)
                            DataGridViewRowValues.SetValue<string>(dr, PL_JournalEntryDetail.Description, desc.Replace(oldText, txtDescription.Text));
                    }
                }
            }
        }

        private void ctbDate_Validating(object sender, CancelEventArgs e)
        {
            if (dbManager.Status != DBMode.Browse && IsNew)
            {
                if (ctbDate.Today.Year != GlobalInfo.CurrentDate.Year)
                    MyMessageBox(string.Format(Properties.Resources.Msg_WrongYear, ctbDate.Today.ToShortDateString(), GlobalInfo.CurrentDate.Year),
                        Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
    }

    #region DbManager dbmanagerJournalEntries

    /// <summary>
    /// Classe derivata per gestioni particolari
    /// </summary>
    public class dbmanagerJournalEntries : DBManager
    {
        public dbmanagerJournalEntries(string name, RadarForm radar, DocumentForm document)
            : base(name, radar, document)
        {
            ForeignKey = PL_JournalEntry.JournalNo;
        }

        public bool IsEditable { get; set; }

        protected override SqlABCommand CreateMasterCommand(ref List<SqlABParameter> dParam)
        {
            return base.CreateMasterCommand(ref dParam);
        }

        protected override List<SqlABParameter> CreateMasterParam()
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();

            SqlABParameter sParam = new SqlABParameter("@p1", PL_JournalEntry.JournalNo);
            sParam.Value = PL_JournalEntry.JournalNo.DefaultValue;
            PList.Add(sParam);
            return PList;
        }

        protected override string CreateMasterQuery()
        {
            this.Table = new PL_JournalEntry();
            QueryBuilder qB = new QueryBuilder();
            qB.AddSelect();
            qB.AddFrom(this.Table);
            qB.AddCompare(PL_JournalEntryDetail.JournalNo, "@p1");

            return qB.Query;
        }

        protected override List<SqlABParameter> CreateSlaveParam(string name)
        {
            if (name == PL_JournalEntryDetail.Name)
            {
                List<SqlABParameter> PList = new List<SqlABParameter>();

                SqlABParameter sParam = new SqlABParameter("@p2", PL_JournalEntryDetail.JournalNo);
                sParam.Value = "";
                PList.Add(sParam);
                return PList;
            }

            if (name == PL_JournalEntryTaxDetail.Name)
            {
                List<SqlABParameter> PList = new List<SqlABParameter>();

                SqlABParameter sParam = new SqlABParameter("@p3", PL_JournalEntryTaxDetail.JournalNo);
                sParam.Value = "";
                PList.Add(sParam);
                return PList;
            }
            return null;
        }

        protected override string CreateSlaveQuery(string name)
        {
            if (name == PL_JournalEntryDetail.Name)
            {
                QueryBuilder qB = new QueryBuilder();
                qB.AddSelect();
                qB.AddFrom(PL_JournalEntryDetail.Name);
                qB.AddCompare(PL_JournalEntryDetail.JournalNo, "@p2");
                qB.AddOrder(PL_JournalEntryDetail.Line);
                return qB.Query;
            }

            if (name == PL_JournalEntryTaxDetail.Name)
            {
                QueryBuilder qB = new QueryBuilder();
                qB.AddSelect();
                qB.AddFrom(PL_JournalEntryTaxDetail.Name);
                qB.AddCompare(PL_JournalEntryTaxDetail.JournalNo, "@p3");
                qB.AddOrder(PL_JournalEntryTaxDetail.Line);
                return qB.Query;
            }
            return "";
        }

        protected override void dAdapter_MasterRowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            if (e.StatementType == StatementType.Insert)
            {
                if (e.Row[PL_JournalEntry.Editable.Name] == System.DBNull.Value)
                    e.Row[PL_JournalEntry.Editable.Name] = 1;
            }
            base.dAdapter_MasterRowUpdating(sender, e);
        }

        protected override void dAdapter_RowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            if (e.StatementType == StatementType.Insert)
            {
                if (e.Row.Table.ToString() == PL_JournalEntryDetail.Name)
                    e.Row[PL_JournalEntryDetail.JournalNo.Name] = GetColumn<string>(PL_JournalEntry.JournalNo, Pos);

                if (e.Row.Table.ToString() == PL_JournalEntryTaxDetail.Name)
                    e.Row[PL_JournalEntryTaxDetail.JournalNo.Name] = GetColumn<string>(PL_JournalEntry.JournalNo, Pos);
            }
            base.dAdapter_RowUpdating(sender, e);
        }

        protected override void SetParameters(IRadarParameters key, DBCollection collection)
        {
            collection.Parameter[0].Value = key[0];
        }
    }

    #endregion

    internal class Totals
    {
        public Totals(string docNo, string type, string code, double from, double to)
        {
            this.DocNo = docNo;
            this.Type = type;
            this.Code = code;
            totFrom = from;
            totTo = to;
        }

        public string Code { get; private set; }
        public string DocNo { get; private set; }
        public double totFrom { get; set; }
        public double totTo { get; set; }
        public string Type { get; private set; }
    }
}